package com.huajx.tb.handler;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import com.huajx.util.convert.Convert;
import org.apache.mina.core.session.IoSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.huajx.core.handler.HandlerAdapter;
import com.huajx.core.message.RequestMessage;
import com.huajx.core.message.ResponseMessage;
import com.huajx.core.util.MessageKit;
import com.huajx.tb.dto.NengLongMessage;

public class CallCheckHandler extends AbstractNengLongHandler {
    protected final Logger logger = LoggerFactory.getLogger(CallCheckHandler.class);

    public final static HandlerAdapter me = new CallCheckHandler();

    private final static String controllerKey = "/di/call/ringUp";

    @Override
    public ResponseMessage handler(RequestMessage request) {

        NengLongMessage dto = getMessage(request.getMessage());
        byte[] bytes = dto.getBody();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        System.out.println("解析完成时间 -" + df.format(new Date()));// new Date()为获取当前系统时间
        String studentCode = MessageKit.getStr(bytes, 32, 20).trim();
        //学校编号
        String schoolCode = dto.getDeviceId().substring(0, 9);
        Map<String, String> paras = new HashMap<>();
        paras.put("content", MessageKit.bytesToString(bytes));
        paras.put("schoolId", schoolCode);
        paras.put("code", studentCode);
        logger.info("解析通话请求解析出schooLId学校编号 {},code学生ID {}", schoolCode, studentCode);
        logger.info("信息接口地址  {}", controllerKey);
        // 处理卡点数据
        try {
            Object obj = post(controllerKey, paras);
//            System.out.println("返回时间 -"+df.format(new Date()));// new Date()为获取当前系统时间
            logger.info("信息接口返回信息  {}", Convert.toStr(obj));
            render(request.getSession(), bytes, Convert.toStr(obj));
        } catch (IOException e) {
            e.printStackTrace();
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i <= 165; i++) {
                sb.append(" ");
            }
            render(request.getSession(), dto, sb.toString());
        }
        return null;
    }

    /**
     * 应答语法
     * 后台拼接好包长+功能号+包体+较验码
     *
     * @param session 会话
     * @param bytes   响应包
     * @param content 内容
     */
    @Override
    protected void render(IoSession session, byte[] bytes, String content) {
        String commonStr = MessageKit.getStr(bytes, 3, 23); // 公共部分 序号 + 协议版本号 + 机器号
        StringBuilder sb = new StringBuilder();
        sb.append(RETURN_COMMAND).append(commonStr).append(content);
        logger.info("返回命令, {}", sb);
        session.write(sb.toString());
    }
//    /**
//     * 应答语法
//     * 后台拼接好包长+功能号+包体+较验码
//     *
//     * @param session
//     * @param bytes
//     * @param content
//     */
//    protected void render(IoSession session, NengLongMessage dto, String content) {
//    	 byte[] bytes = dto.getBody();
//         String m = MessageKit.getStr(bytes, 3, 23);
//         int len = null == content ? 2 : content.length() + 2;
//         String lenHex = MessageKit.intToHex(len, '0', 4);
//         String command = dto.getCommand();
//         String checksum = MessageKit.checksum(command + content);
//         StringBuilder sb = new StringBuilder();
//         sb.append(RETURN_COMMAND).append(m).append(lenHex).append(command).append(content).append(checksum);
//         logger.info("返回命令, {}", sb);
//         try {
// 			session.write(sb.toString().getBytes("GB2312"));
//		 } catch (UnsupportedEncodingException e) {
// 			// TODO Auto-generated catch block
// 			e.printStackTrace();
// 		}
//    }
//
//    @Override
//    protected void render(IoSession session, byte[] bytes, String content) {
//        String m = MessageKit.getStr(bytes, 3, 23);
//        StringBuilder sb = new StringBuilder();
//        sb.append(RETURN_COMMAND).append(m).append(content);
//        logger.info("返回命令, {}", sb);
//        try {
//			session.write(sb.toString().getBytes("GB2312"));
//		} catch (UnsupportedEncodingException e) {
//			e.printStackTrace();
//		}
//    }


}
